<?php
namespace app\crm\controller;
use app\common\controller\UserBase; 
use app\crm\model\CrmCustomer;
use app\crm\model\CrmContact;
use app\crm\model\CrmUser;
use app\user\model\FieldData;
use app\user\model\User;

class Contact extends UserBase
{
    public function initialize()
    {
        parent::initialize();
        //获取客服列表
        $this->contact = get_dict_list('6');
    }
    //添加客户
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['user_id'] = UserId();
            $param['shop_id'] = ShopId();
            $param['jdata'] = $param;
            $result = CrmCustomer::create($param);
            if ($result == true) {
                //客服绑定
                CrmUser::update_user($param['kefu'],$param['id']);
                insert_user_log('添加了客户信息');
                $this->success('添加成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        
        return $this->fetch('save', [
            'field'     => $this->field,
            'kefu'      => $this->kefu,
            'user_list' => $this->user_list
        ]);
    }
    //编辑联系人
    public function edit($id)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = CrmContact::update($param,['id'=>$param['id']]);
            if ($result == true) {
                insert_user_log('修改了客户联系人信息');
                $this->success('修改成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data = CrmContact::where('id', $id)->find();
        return $this->fetch('save', [
            'data'      => $data,
            'contact'   => $this->contact
        ]);
    }
    //删除客户
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            CrmContact::destroy($param['id']);
            insert_user_log('删除了联系人');
            $this->success('删除成功');
        }
    }
    //
    public function detail($id)
    {   
        $customer = new CrmCustomer();
        //获取数据
        $data = $customer->with(['crmuser','contact'])->where('id',$id)->find();
        
   //     $this->result($data);
        return $this->fetch('detail',[
            'data'  => $data,
            'field' => $this->field,
            'kefu'  => $this->kefu,
        ]);
    }
    
    
    
}
